package com.strato.mybatis.generator.v1_2_0.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

public class GenerateConfig {

	public static GenerateConfig instance=null;
	
	public synchronized static GenerateConfig getInstance(){
		if(instance==null){
			instance=new GenerateConfig();
		}
		return instance;
	}

	private Properties properties;
	
	private GenerateConfig(){
		InputStream is = GenerateConfig.class.getResourceAsStream("/generate.properties");
		Properties p=new Properties();
		try {
			p.load(is);
			is.close();
			this.properties=p;
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		_parse();
	}

	private Map<String,Database> databases=new LinkedHashMap<String,Database>();
	
	private void _parse() {
		String sdbnames=properties.getProperty("database.list");
		String[] dbnames=sdbnames.split(",");
		for(String dbname:dbnames){
			Database db=new Database();
			db.setName(dbname);
			String driver=properties.getProperty("database."+dbname+".driver");
			db.setDriver(driver);
			String url=properties.getProperty("database."+dbname+".url");
			db.setUrl(url);
			String username=properties.getProperty("database."+dbname+".username");
			db.setUsername(username);
			String password=properties.getProperty("database."+dbname+".password");
			db.setPassword(password);
			databases.put(dbname, db);
		}
	}

	public Map<String, Database> getDatabases() {
		return databases;
	}

	public Properties getProperties() {
		return properties;
	}
	
	public String tableName2ClassName(String tableName){
		String prefixs=getProperties().getProperty("attribute.tableName.prefix");
		if(prefixs==null||prefixs.equals(tableName)){
			return tableName2ClassName(tableName,new String[]{});
		}else{
			return tableName2ClassName(tableName, prefixs.split(","));
		}
	}
	
	private String tableName2ClassName(String tableName, String[] prefixes) {
		for(int i=0;i<prefixes.length;i++){
			String prefix=prefixes[i];
			if(tableName.startsWith(prefix)){
				tableName=tableName.substring(prefix.length());
				break;
			}
		}
		String[] parts=tableName.split("_");
		StringBuffer buf=new StringBuffer();
		for(String part:parts){
			if("".equals(part)){
				continue;
			}
			String firstChar=""+part.charAt(0);
			buf.append(firstChar.toUpperCase()).append(part.substring(1));
		}
		return buf.toString();
	}

	public static void main(String[] a){
		Map<String, Database> dbs = GenerateConfig.getInstance().getDatabases();
		System.out.println(dbs);
		System.out.println("=====================");
		Properties p = GenerateConfig.getInstance().getProperties();
		p.list(System.out);
		System.out.println(GenerateConfig.getInstance().tableName2ClassName("sys_user_info"));
	}
	
}
